package file;

import java.io.*;
import java.util.Scanner;



/**
 * Created with IntelliJ IDEA.
 * Description: 遍历目录，找到文件名或文件内容内包含关键字的文件并且打印出路径
 * User: 王圆豪
 * Date: 2025-05-12
 * Time: 20:04
 */
public class Demo15 {
    public static void main(String[] args) {
        //输入根目录及关键字
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你要在哪个目录中遍历：");
        String s1 = sc.next();
        File file = new File(s1);
        if (!file.isDirectory()) {
            System.out.println("此目录不存在！");
            return;
        }
        System.out.println("请输入关键字：");
        String s2 = sc.next();

        scanDir(file, s2);
    }

    private static void scanDir(File file, String s2) {
        File[] files = file.listFiles();
        if(files == null) return;
        for (File tmp:
             files) {
            if (tmp.isFile()) {
                dealFile(tmp, s2);
            }else {
                scanDir(tmp, s2);
            }
        }
    }

    private static void dealFile(File tmp, String s2) {
        if (tmp.getName().contains(s2)){
            System.out.println("关键字所在文件：" + tmp.getAbsolutePath());
            return;
        }
        try (Reader reader = new FileReader(tmp)){
            StringBuilder stringBuilder = new StringBuilder();
               while (true) {
                   char[] chars = new char[1024];
                   int n = reader.read(chars);
                   if (n == -1) break;
                   for (int i = 0; i < n; i++) {
                       stringBuilder.append(chars,0,n);
                   }
                   if (stringBuilder.toString().contains(s2)){
                       System.out.println("关键字所在文件：" + tmp.getAbsolutePath());
                       return;
                   }
               }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
